/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 7/9/13
 * Time: 16:48
 * To change this template use File | Settings | File Templates.
 */

var dao = require('../dao/index.js');
var async = require('async');

function createPostTags(req) {
    var arr = req.body.tags.split(',');
    arr.forEach(function(tag, index) {
        tag = arr[index] = tag.toLocaleLowerCase();
        dao.category.getOneBySlug(tag).then(function(doc) {
            if (!doc) {
                dao.category.create({
                    name : tag,
                    slug : tag
                }).then(function(doc) {
                    if (doc) {
                        console.log('createPostTags ' + tag + ' 创建成功');
                    }
                });
            }
        });
    });
    req.body.tags = arr;
}

exports.index = function(req, res) {
    var slug = req.param('slug');
    var locals = {};
    async.waterfall([
    function(done) {
        dao.category.getList().then(function(categories) {
            done(null, categories);
        });
    },
    function(categories, done) {
        locals.categories = categories;
        dao.post.getOneBySlug(slug).then(function(post) {
            done(null, post);
        });
    },
    function(post, done) {
        locals.post = post;
        locals.category = post.category;
        done(null, post);
    }], function() {
        res.render('article', locals);
    });
};
exports.create = function(req, res) {
    if (!res.locals.user || !res.locals.user._id) {
        res.redirect('/signin');
    } else {
        if (req.method == 'GET') {
            dao.category.getList().then(function(categories) {
                res.render('article-add', {
                    'title' : 'Express',
                    'categories' : categories,
                    'category' : {}
                });
            });
        } else {
            createPostTags(req);
            dao.post.create(req.body).then(function(doc) {
                res.json(doc);
            });
        }
    }
};
